<?php
if(!defined('IN_BSTO')){ die('[ERROR] You cannot load this page directly !!!'); }

Class ContactusController Extends BaseController {
	private $errorList = array();
	private $valueList = array();
	function __construct($registry)
	{
		parent::__construct($registry);
		$this->errorList['name'] = '';
		$this->errorList['message'] = '';
		$this->errorList['email'] = '';
		$this->errorList['phone'] = '';
		$this->errorList['company'] = '';
		$this->errorList['inform'] = '';
		$this->valueList['value_name'] = '';
		$this->valueList['value_email'] = '';
		$this->valueList['value_phone'] = '';
		$this->valueList['value_company'] = '';
		$this->valueList['value_message'] = '';
	}
	public function okie(){
		if($this->errorList['name']==''&& $this->errorList['email']==''&& $this->errorList['phone']==''&& $this->errorList['company']==''&& $this->errorList['message']=='')
			return true;
		return false;
	}
	public function get_post_info()
	{
		$this->valueList['value_name'] = isset($_POST['name'])? $_POST['name']:'';
		$this->valueList['value_email'] = isset($_POST['email'])? $_POST['email']:'';
		$this->valueList['value_phone'] = isset($_POST['phone'])? $_POST['phone']:'';
		$this->valueList['value_company'] = isset($_POST['company'])? $_POST['company']:'';
		$this->valueList['value_message'] = isset($_POST['message'])? $_POST['message']:'';
	}
    public function index() 
    {
    	
    	$method = $_SERVER['REQUEST_METHOD'];    	
    	if ($method=='POST'){     
    		if (!filter_var($_POST['name'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/[a-zA-Z][a-zA-Z' ']/")))){
    			$this->errorList['phone'] = "Please choose a valid name.<br/>";
    		}		           
    		if (!filter_var($_POST['phone'], FILTER_VALIDATE_FLOAT)){
    			$this->errorList['phone'] = "Please use a valid phone number.<br/>";
    		}
    		if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
    			$this->errorList['email'] = "Please use a valid email format.<br/>";
    		}
    		if (strlen($_POST['message']) > 140){
    			$this->errorList['message'] = "Please shorten your message.<br/>";
    		}
    		while (list($key, $val) = each($_POST))
    		{
    			if ( trim($val) == '' && $key == 'name' ) {
    				$this->errorList[$key] = "Please enter your name.<br/>";
    			}
    			if ( trim($val) == '' && $key == 'email' ) {
    				$this->errorList[$key] = "Please enter your email.<br/>";
    			}
    			if ( trim($val) == '' && $key == 'message' ) {
    				$this->errorList[$key] = "Please enter your message content.<br/>";
    			}
    		}
    		if(trim($_POST['phone'])==''){
    			$this->errorList['phone']='';
    		}
    		if($this->okie()){    		
    			
    			
    			include('Mail-1.2.0/Mail.php');
		        include('Mail-1.2.0/Mail/mime.php');
		
		        // Send confirmation email to visitor
		        $mailPath = BSTO_PATH.'/views/mailContactClient.html';
		       
		        $sender = "pyco24@bsto.com";                             
		        $recipient = $_POST['email'];                           
		        $subject = "[Book Store]Message Confirmation.";                                
		        $html = file_get_contents($mailPath);
	    		foreach($_POST as $tag => $value){
					$html = str_replace('{'.$tag.'}', $value, $html);
				}
		        $text = strip_tags($html);  
		        $crlf = "\n";
		        $headers = array(
		                        'From'          => $sender,
		                        'Return-Path'   => $sender,
		                        'Subject'       => $subject
		                        );
		
		        // Creating the Mime message
		        $mime = new Mail_mime($crlf);
		
		        // Setting the body of the email
		        $mime->setTXTBody($text);
		        $mime->setHTMLBody($html);
		
		        $body = $mime->get();
		        $headers = $mime->headers($headers);

		        // Sending the email
		        $mail =& Mail::factory('mail');
		        $mail->send($recipient, $headers, $body);
		        
		        // Sending email to admin(s)
		        $mailPath = BSTO_PATH.'/views/mailContactAdmin.html';
		        $recipient = "";
    			$adminList = $this->registry->db->get('userManager')->filter('type', 'Admin');
    			foreach ($adminList as $admin)
    			{
    				$recipient = $recipient.$admin->get('email').', ';
    			}
    			$subject = "[Book Store]CONTACT US Message.";  
    			$html = file_get_contents($mailPath);
	    		foreach($_POST as $tag => $value){
					$html = str_replace('{'.$tag.'}', $value, $html);
				}				
		        $text = strip_tags($html); 
		        $headers['Subject'] = $subject;
		        
		        // Creating the Mime message
		        $mime = new Mail_mime($crlf);
		        
		        // Setting the body of the email
		        $mime->setTXTBody($text);
		        $mime->setHTMLBody($html);
		
		        $body = $mime->get();
		        $headers = $mime->headers($headers);

		        // Sending the email
		        $mail =& Mail::factory('mail');
		        $mail->send($recipient, $headers, $body);
		        $mail = Mail::factory("mail");

    			/*$headers = array("From"=>"me@example.com", "Subject"=>"Test Mail");
    			$body = "This is a test!";
    			$mail->send("hnguyen9x@gmail.com", $headers, $body);*/
		        $inform = 'Your message has been sent successfully.';
				$this->errorList['inform'] = $inform;
				$content = $this->registry->template->getTemplate('contactusForm', array_merge($this->errorList, $this->valueList), 'Module');
    		//echo $content;
    		
            $this->registry->template->setMenuKey('contact');
    		$tags = array('bstoHead'=>"");
	    	$user = $this->registry->db->get('userManager')->getCurrentUser();
	        if($user != null){
	        	$tags['login'] = '<li id="login"><span> Hello, '. $user->get('username').'</span><a href="{bstoRootPath}logout">Logout</a></li>';	
	        }else{
	        	$tags['login'] = '<li id="login"><a href="{bstoRootPath}login">Login</a></li>';
	        }
    		echo $this->registry->template->getPageContent('index', 'Contact us', $content, $tags);
	    			
    		}
    		
    	}
    	if(($method=='POST'&& !$this->okie())||$method !='POST'){
    		$this->get_post_info();   		
    		$content = $this->registry->template->getTemplate('contactusForm', array_merge($this->errorList, $this->valueList), 'Module');
    		//echo $content;
    		
            $this->registry->template->setMenuKey('contact');
    		$tags = array('bstoHead'=>"");
	    	$user = $this->registry->db->get('userManager')->getCurrentUser();
	        if($user != null){
	        	$tags['login'] = '<li id="login"><span> Hello, '. $user->get('username').'</span><a href="{bstoRootPath}logout">Logout</a></li>';	
	        }else{
	        	$tags['login'] = '<li id="login"><a href="{bstoRootPath}login">Login</a></li>';
	        }
    		echo $this->registry->template->getPageContent('index', 'Contact us', $content, $tags);
    	}
    }
}
?>